<template>
    <view class="custom-tab-bar">
        <view class="tab-bar">
            <view v-for="(item, index) in tabBarList" :key="index" class="tab-bar-item"
                :class="{ active: currentIndex === index }" @click="switchTab(index, item.pagePath)">
                <uni-icons 
                    :type="item.icon" 
                    :color="currentIndex === index ? '#007AFF' : '#7A7E83'" 
                    size="24" 
                />
                <text class="tab-bar-text">{{ item.text }}</text>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue';

// 定义响应式数据
const currentIndex = ref(0)
const tabBarList = ref([
    {
        pagePath: 'views/home/menu',
        text: '首页',
        icon: 'home'
    },
    {
        pagePath: 'views/ui/uniui-demo',
        text: '客户',
        icon: 'paperplane'
    },
    {
        pagePath: 'views/api/api-demo',
        text: '报表',
        icon: 'paperplane'
    },
    {
        pagePath: 'views/user/user',
        text: '我的',
        icon: 'person'
    }
])

// 更新当前选中索引
const updateCurrentIndex = (path) => {
    tabBarList.value.forEach((item, index) => {
        if (item.pagePath === path) {
            currentIndex.value = index
        }
    })
}

// 页面切换方法
const switchTab = (index, path) => {
    console.log('switchTab', index, path)
    currentIndex.value = index
    // 使用switchTab导航到tab页面
    uni.switchTab({
        url: '/' + path
    })
}

// 组件挂载后执行
onMounted(() => {
    // 获取当前页面路径，设置当前选中项
    const pages = getCurrentPages()
    if (pages.length > 0) {
        const currentPage = pages[pages.length - 1]
        const route = currentPage.route
        updateCurrentIndex(route)
    }
    
    // 监听页面显示事件
    uni.$on('updateTabBar', (path) => {
        updateCurrentIndex(path)
    })
})

// 组件卸载前执行
onUnmounted(() => {
    // 移除事件监听
    uni.$off('updateTabBar')
})
</script>

<style>
.custom-tab-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 60px;
    background-color: #ffffff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 9999;
}

.tab-bar {
    display: flex;
    height: 100%;
    width: 100%;
}

.tab-bar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.tab-bar-text {
    font-size: 14px;
    margin-top: 4px;
    color: #7A7E83;
}

.tab-bar-item.active .tab-bar-text {
    color: #007AFF;
}

/* 确保图标和文字居中 */
.tab-bar-item uni-icons {
    display: flex;
    justify-content: center;
    align-items: center;
}
</style>